<!-- eslint-disable vue/html-self-closing -->
<template>
  <div class="app-container">
    <div class="left">
      <header style="margin-bottom:10px">
        <el-input
          v-model="input"
          size="small"
          placeholder="输入员工姓名全员搜索"
          prefix-icon="el-icon-search"
        ></el-input>
      </header>
      <section>
        <el-tree
          :data="data"
          :props="defaultProps"
          :default-expand-all="true"
          :expand-on-click-node="false"
          node-key="id"
          :highlight-current="true"
          :current-node-key="1"
          @node-click="handleNodeClick"
        ></el-tree>
      </section>
    </div>
    <div class="right">
      <header>
        <Tips>
          <!-- <template v-slot:left>有 0 条考勤审批尚未处理</template> -->
          <template v-slot:right>
            <el-button
              v-judge-auth="'employeeAdd'"
              size="mini"
              type="primary"
              @click="addEmployee"
            >添加员工</el-button>
            <el-button
              v-judge-auth="'employeeAdd'"
              size="mini"
              @click="$refs.importExcel.open()"
            >excel导入</el-button>
            <el-button
              v-judge-auth="'employeeExport'"
              size="mini"
              @click="importEmployeeExcel"
            >excel导出</el-button>
          </template>
        </Tips>

        <!-- 导入 -->
        <importExcel ref="importExcel" @success="success"></importExcel>
      </header>
      <section>
        <el-table :data="tableData" style="width: 100%" :default-sort="{ order: 'descending'}">
          <el-table-column align="center" prop="date" label="头像" width="110">
            <template slot-scope="scope">
              <img
                v-if="scope.row.staffPhoto"
                style="height: 30px;width: 30px; border-radius: 50%;"
                :src="scope.row.staffPhoto"
                alt
              />
              <span v-else class="staff">{{ scope.row.username | substr }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="username" label="姓名" width="110" />
          <el-table-column align="center" prop="mobile" label="手机号" sortable width="110" />
          <el-table-column align="center" prop="workNumber" label="工号" sortable width="110" />
          <el-table-column
            align="center"
            label="聘用形式"
            width="110"
            prop="formOfEmployment"
            :formatter="formateFormofEmployment"
          />
          <el-table-column
            align="center"
            prop="departmentId"
            :formatter="formateFormofDepartment"
            label="部门"
            width="110"
          />
          <el-table-column align="center" prop="timeOfEntry" label="入职时间" sortable width="110" />
          <el-table-column prop="address" label="操作" :formatter="formatter" width="250">
            <template slot-scope="scope">
              <el-button
                v-judge-auth="'employeeEdit'"
                type="text"
                size="small"
                @click="handleClick(scope.row)"
              >查看</el-button>
              <el-button
                v-judge-auth="'employeeDistributeRole'"
                type="text"
                size="small"
                @click="roleFn(scope.row.id)"
              >角色</el-button>
              <el-popconfirm
                style="margin-left: 10px"
                title="这是一段内容确定删除吗？"
                @onConfirm="delFn(scope.row.id)"
              >
                <el-button slot="reference" v-judge-auth="'employeeDel'" type="text" size="small">删除</el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <!-- 角色窗口 -->
        <distributionRole ref="distributionRole"></distributionRole>

        <div class="block" style="float: right;">
          <el-pagination
            :current-page.sync="currentPage"
            :page-size="pageSize"
            layout="total, prev, pager, next"
            :total="total"
            @current-change="handleCurrentChange"
          ></el-pagination>
        </div>
      </section>
    </div>
  </div>
</template>
<script>
import { getEmployeeList, delEmployee, getEmployeeExcel } from '@/api/employee'
import { getDepartmentList } from '@/api/department'
import { dataToTree } from '@/utils/tools'
import Tips from '@/components/Tips'
import distributionRole from './components/distributionRole.vue'
import { saveAs } from 'file-saver'
import importExcel from './components/importExcel.vue'

export default {
  name: 'Employee',
  components: {
    Tips,
    distributionRole,
    importExcel
  },
  filters: {
    substr: function(value) {
      return value.substring(0, 1)
    }
  },
  data() {
    return {
      tableData: [],
      currentPage: 1,
      input: '', // 输出框的内容
      data: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      total: 0, // 总条数
      pageSize: 4, // 每页显示的条数
      List: [], // 部门列表
      timeOut: null, // 延时器用来做防抖
      departmentId: 1 // 记录是那个部门的员工
    }
  },
  watch: {
    input(newVal, oldVal) {
      this.currentPage = 1
      if (this.timeOut) {
        clearTimeout(this.timeOut)
        this.timeOut = null
      }
      this.timeOut = setTimeout(() => {
        this.getEmployeeList()
      }, 1000)
    }
  },
  created() {
  },
  mounted() {
    this.getDepartmentList()
    this.getEmployeeList()
  },
  methods: {
    formatter(row, column) {
      return row.address
    },
    handleClick(row) {
      console.log(row.id)
      this.$router.push(`/addEmployee/detail/${row.id}`)
    },
    async getEmployeeList(departmentId) {
      const { data } = await getEmployeeList({
        page: this.currentPage,
        pagesize: this.pageSize,
        departmentId,
        keyword: this.input
      })
      // 判断当前页面是否有值
      if (data.rows.length === 0 && this.currentPage > 1) {
        this.currentPage--
        this.getEmployeeList(this.departmentId)
        return
      }
      // console.log(data)
      // console.log(data)
      this.total = data.total
      this.tableData = data.rows
    },
    // 分页页码变化
    handleCurrentChange(val) {
      this.getEmployeeList(this.departmentId)
    },
    async getDepartmentList() {
      const res = await getDepartmentList()
      // console.log(res)
      // console.log(...res.data)
      // console.log(this.defaultProps)
      this.List = res.data
      this.data = dataToTree(res.data)
    },
    handleNodeClick(data) {
      console.log(data)
      this.currentPage = 1
      this.departmentId = data.id
      this.getEmployeeList(this.departmentId)
    },
    formateFormofEmployment(row, column, cellValue, index) {
      // console.log(cellValue)
      return cellValue === 1 ? '正式' : '非正式'
    },
    formateFormofDepartment(row, column, cellValue, index) {
      // console.log(cellValue)
      // console.log(this.tableData)
      // console.log(this.List)
      if (this.List.length === 0) return
      // console.log(cellValue)
      // console.log(row)
      const obj = this.List.find(item => item.id === cellValue)
      return obj.name
    },
    roleFn(id) {
      this.$refs.distributionRole.open(id)
    },
    // 删除角色
    async delFn(id) {
      console.log(id)
      await delEmployee(id)
      this.$message.success('删除角色成功！')
      this.getEmployeeList()
    },
    // 添加员工
    addEmployee() {
      console.log(1)
      this.$router.push('/addEmployee/detail')
    },
    // excel表格导出
    async importEmployeeExcel() {
      const res = await getEmployeeExcel({
      })
      console.log(res)
      saveAs(res, '员工列表.xlsx')
    },
    // 导入文件成功后刷新
    success() {
      this.currentPage = Math.ceil((this.total + 1) / this.pageSize)
      this.currentPage = Math.floor(this.total / this.pageSize) + 1
      this.getEmployeeList(this.departmentId)
    }

  }
}
</script>

<style lang="scss" scoped>
.app-container {
  display: flex;
  .left {
    width: 263px;
    padding: 20px;
    border-right: 1px solid #eaeef4;
  }
  .right {
    flex: 1;
    padding: 20px;
  }
}
::v-deep .staff {
  height: 30px;
  width: 30px;
  line-height: 30px;
  text-align: center;
  border-radius: 50%;
  color: #fff;
  background: #04c9be;
  font-size: 12px;
  display: inline-block;
}
</style>
